var express = require('express');
var router = express.Router();
const { Article } = require('../models');
const { NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            attributes: {exclude: ['content']},
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize
        }
        // if (query.title) {
        //     condition.where = {
        //         title: {
        //             [Op.like]: `%${query.title}%`
        //         }
        //     }
        // }
        const { count, rows } = await Article.findAndCountAll(condition);
        success(
            res,
            '查询文章列表成功',
            {
                article: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询文章详情
router.get('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req);
        success(
            res,
            '查询文章成功',
            {article}
        )

    } catch (error) {
        failure(res, error)
    }
});

/**
 * 查询当前文章
 * @param {*} req 
 */
async function getArticle(req) {
    const { id } = req.params;
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID: ${id}的文章未找到`)
    }
    return article;
}

module.exports = router;
